/*!
 * \file mediawhere.c
 * \brief This is the mediawhere's FILEBACKEND for real-time monitoring of filesytem.
 * Mediawhere is an application (search tool) that allows you to keep track of files on the file system,
 * indexing the text within them and integrating  additional information (media tag) about their contents
 * to help you in searching. He is able to do simply these things:
 *
 * - 1 Real-time monitoring of moving, renaming, editing, creation and deletion in your home directory of pdf/txt/doc/mp3/jpeg/jpg file
 * - 2 Identify file (pdf, doc, txt) and its path according to the text inside it (indexing process)
 * - 3 Extract media file's tags and use them in searching.
 * 
 * \author Gioacchino Bombaci, Giuseppe Caratozzolo, Antonio Caristia
 * \date 31/01/2011
 */




#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <inotifytools/inotifytools.h> 
#include <inotifytools/inotify.h>

#define NUM_TYPE_FILE 9 /*!<  The number of file extensions under control  */
#define BUFFER 4096 /*!<  char buffer */

int in_create(struct inotify_event * event, char *path, char* found_dir, char **type_file_list);
int in_create_isindir(struct inotify_event * event, char *path, char *found_dir);
int in_delete(int wd, char *path, char *name, char **type_list, char *found_dir);
int in_delete_isindir(int wd, char *path, char *name, char **type_list, char *found_dir);
int in_moved_from(struct inotify_event *event, int wd, char *path, char *name, char **type_list, char *found_dir);
int in_moved_to(struct inotify_event *event, int wd, char *path, char *name, char **type_list, char *found_dir);
int in_modify(struct inotify_event * event, char *path, char **type_list);
void to_upper_case(char *string);

int main(int argc, char **argv)
{

	int indexing,config;
	char conf_filename[BUFFER];//config file

	//set install dir found=$HOME/.mediawhere/found/
	char *found_dir = (char *)malloc(BUFFER*sizeof(char));
	char *home_dir = getenv("HOME");
	strcpy(found_dir, home_dir);
	strcat(found_dir, "/.mediawhere/found/");


	if(argc<2)
	{
		printf("\n%s%s%s%s\n",
		"Usage:	", argv[0], " {index|noindex} {conf|noconf}\n",
		"you should use index only first time\n");
		exit(1);
	}
	
	if(strcmp(argv[1], "index")==0)
		indexing = 0; //true...yes indexing
	else if(strcmp(argv[1], "noindex")==0)
		indexing = 1;//false...no indexing
	else
	{
		printf("Abort...error input parameter\n\a");
		exit(1);
	}

	if(strcmp(argv[2], "conf")==0)
	{
		config = 0;
		//set config filename
		strcpy(conf_filename, home_dir);
		strcat(conf_filename, "/.mediawhere/config");

	}
	else if(strcmp(argv[2], "noconf")==0)
	{
		config = 1;
	}
	
		
	FILE *fp[NUM_TYPE_FILE];
	FILE *dir;


	//init typelist
	char *type_file_list[NUM_TYPE_FILE] = {"avi", "mp3", "pdf", "txt", "jpeg", "jpg", "doc", "epub", "odt"};

	//init inotify
	if(!inotifytools_initialize())
	{
		 fprintf(stderr, "%s\n", strerror( inotifytools_error() ));
		 return -1;
	}
	
	if( (indexing==0) && (config==0) )//indexing and config_file
	{
		int i;

		FILE *config = fopen(conf_filename,"r");//opening config file

		
		//remove old indexing
		/*
		char *remove_old_index = (char *)malloc(BUFFER*sizeof(char));
		for(i=0; i<NUM_TYPE_FILE; i++)
		{
			strcpy(remove_old_index, "rm $HOME/.mediawhere/found/");
			strcat(remove_old_index, type_file_list[i]);
			system(remove_old_index);
		}
		*/

		//reading config file and searching files under control 
		char selected_dir_toindex[BUFFER];
		fgets(selected_dir_toindex, BUFFER, config);
		if(selected_dir_toindex[strlen(selected_dir_toindex)-1]=='\n')
			selected_dir_toindex[strlen(selected_dir_toindex)-1]='\0';//delete \n
		while(!feof(config))
		{
			//$HOME/.mediawhere/found/cercafileinconfig.sh /percorso/dir
			char *find_cmd = (char *)malloc(BUFFER*sizeof(char));
			strcpy(find_cmd, "$HOME/.mediawhere/found/cercafileinconfig.sh ");
			strcat(find_cmd, selected_dir_toindex);
			system(find_cmd);

			fgets(selected_dir_toindex, BUFFER, config);
			if(selected_dir_toindex[strlen(selected_dir_toindex)-1]=='\n')
				selected_dir_toindex[strlen(selected_dir_toindex)-1]='\0';
		}
		
		fclose(config);

		//removing old dir
		/*
		char *del_sub_dir =(char *)malloc(BUFFER*sizeof(char));
		strcpy(del_sub_dir, "rm $HOME/.mediawhere/found/homesubdir");
		system(del_sub_dir);
		free(del_sub_dir);
		*/

		//creating new dir file
		FILE *conf_file = fopen(conf_filename,"r");//opening config file
		char selected_dir[BUFFER];
		fgets(selected_dir, BUFFER, conf_file);
		if(selected_dir[strlen(selected_dir)-1]=='\n')
			selected_dir[strlen(selected_dir)-1]='\0';//delete \n
		while(!feof(conf_file))
		{
			//$HOME/.mediawhere/found/cercafileinconfig.sh /percorso/dir
			char *find_cmd = (char *)malloc(BUFFER*sizeof(char));
			strcpy(find_cmd, "find  ");
			strcat(find_cmd, selected_dir);
			strcat(find_cmd, " -type d >> ");
			strcat(find_cmd, found_dir);
			strcat(find_cmd, "homesubdir");
			
			system(find_cmd);
			free(find_cmd);

			fgets(selected_dir, BUFFER, conf_file);
			if(selected_dir[strlen(selected_dir)-1]=='\n')
				selected_dir[strlen(selected_dir)-1]='\0';
			
		}
		
		fclose(conf_file);
	}
	else if(indexing==0)//indexing and no config_file
	{
		//execute script to find files with type under control
		//cmd1=$HOME/.mediawhere/found/cercafile.sh
		char *cmd1 = (char *)malloc(BUFFER*sizeof(char));
		strcpy(cmd1, found_dir);
		strcat(cmd1, "cercafile.sh");
		system(cmd1);
		
		//execute script to find home' subdir
		//cmd2=find $HOME -type d > $HOME/.mediawhere/found/homesubdir
		char *cmd2 = (char *)malloc(BUFFER*sizeof(char));
		strcpy(cmd2, "find ");
		strcat(cmd2, home_dir);
		strcat(cmd2, " -type d > ");
		strcat(cmd2, found_dir);
		strcat(cmd2, "homesubdir");
		//cerco tutte le dir dentro la home
		system(cmd2);
	}

	//setto il formato per strftime
	inotifytools_set_printf_timefmt("%H:%M:%S");  	

	if(indexing==0)
	{
		//del
		//java -Ddata=args -Dcommit=yes -jar post.jar "<delete><query>*:*</query></delete>"
		char del[BUFFER];
		strcpy(del, "java -Ddata=args -Dcommit=yes -jar ");
		strcat(del, found_dir);
		strcat(del, "post.jar \"<delete><query>*:*</query></delete>\"");
		system(del);			
	}

	//watching file
	int i;
	for(i=0; i<NUM_TYPE_FILE; i++)
	{
		char *dst = (char *)malloc(BUFFER*sizeof(char)); //4096 caratteri
		strcpy(dst, found_dir);
		char *file_name = strcat(dst, type_file_list[i]);
		fp[i]=fopen(file_name, "r");

		char tmp_filename[BUFFER];
		//fscanf(fp[i], "%s", tmp_filename);
		fgets(tmp_filename, BUFFER, fp[i]);
		if(tmp_filename[strlen(tmp_filename)-1]=='\n')
			tmp_filename[strlen(tmp_filename)-1]='\0';//delete \n
		while(!feof(fp[i]))
		{	
			if(indexing==0)//remove all and add file list
			{
			//add...
			//echo "FILEBACKEND|DOC|locahost|/home/kinder/mediawhere/in.txt|INSERT\nQUIT"| nc localhost 7777
			char *tosocket = (char *)malloc(BUFFER*sizeof(char));
			strcpy(tosocket, "echo \"FILEBACKEND|");
			//etx becames EXT
			char upper_string[BUFFER];
			strcpy(upper_string, type_file_list[i]);
			to_upper_case(upper_string);

			strcat(tosocket, upper_string);
			strcat(tosocket, "|localhost|");
			strcat(tosocket, tmp_filename);
			strcat(tosocket, "|INSERT\nQUIT\"| nc localhost 7777");
			printf("[CMD]%s\n", tosocket); 
			system(tosocket);
			}

			if(strcmp(type_file_list[i], "pdf")==0 || strcmp(type_file_list[i], "txt")==0 || strcmp(type_file_list[i], "doc")==0)
			{
				inotifytools_watch_file(tmp_filename, IN_CLOSE_WRITE|IN_MOVE_SELF);
				printf("[Append watch] [file=%s] [event=%s]\n", tmp_filename, "IN_CLOSE_WRITE|IN_MOVE_SELF");
			}
			else
			{			
				inotifytools_watch_file(tmp_filename, IN_MOVE_SELF);
				printf("[Append watch] [file=%s] [event=%s]\n", tmp_filename, "IN_MOVE_SELF");
			}
			//fscanf(fp[i], "%s", tmp_filename);
			fgets(tmp_filename, BUFFER, fp[i]);
			if(tmp_filename[strlen(tmp_filename)-1]=='\n')
				tmp_filename[strlen(tmp_filename)-1]='\0';
		}
		
		fclose(fp[i]);
	}

	//watching dir inside config file
	/*
	if(config==0)
	{
		FILE *config = fopen(conf_filename,"r");//opening config file

		char selected_dir_toindex[BUFFER];
		fgets(selected_dir_toindex, BUFFER, config);
		if(selected_dir_toindex[strlen(selected_dir_toindex)-1]=='\n')
			selected_dir_toindex[strlen(selected_dir_toindex)-1]='\0';//delete \n
		while(!feof(config))
		{
			inotifytools_watch_file(selected_dir_toindex, IN_MOVE_SELF|IN_CREATE|IN_DELETE|IN_MOVE);
			printf("[Append watch] [dir=%s] [event=%s]\n", selected_dir_toindex, "IN_MOVE_SELF|IN_CREATE|IN_DELETE|IN_MOVE");
			fgets(selected_dir_toindex, BUFFER, config);
			if(selected_dir_toindex[strlen(selected_dir_toindex)-1]=='\n')
				selected_dir_toindex[strlen(selected_dir_toindex)-1]='\0';
		}

		fclose(config);
	}
	*/
	
	//open file which contains home' sublist
	//homesublist=/home/user/mediawhere/found/homesubdir
	char *homesublist = (char *)malloc(BUFFER*sizeof(char));
	strcpy(homesublist, found_dir);
	strcat(homesublist, "homesubdir");
	dir = fopen(homesublist, "r");
	char tmp_dirname[1000];
	//fscanf(dir, "%s", tmp_dirname);
	fgets(tmp_dirname, BUFFER, dir);
	if(tmp_dirname[strlen(tmp_dirname)-1]=='\n')
		tmp_dirname[strlen(tmp_dirname)-1]='\0';//delete \n
	while(!feof(dir))
	{		
		inotifytools_watch_file(tmp_dirname, IN_MOVE_SELF|IN_CREATE|IN_DELETE|IN_MOVE);
		printf("[Append watch] [dir=%s] [event=%s]\n", tmp_dirname, "IN_MOVE_SELF|IN_CREATE|IN_DELETE|IN_MOVE");
		//fscanf(dir, "%s", tmp_dirname);
		fgets(tmp_dirname, BUFFER, dir);
		if(tmp_dirname[strlen(tmp_dirname)-1]=='\n')
			tmp_dirname[strlen(tmp_dirname)-1]='\0';
	}
	
	while(1)
	{
		struct inotify_event * event = inotifytools_next_event( -1 );
		
		inotifytools_printf( event, "[%T] [watch=%w] [*=%f][event=%e]\n" );

		if(event->mask == IN_IGNORED)
			continue;

		char *tmp = (char *)malloc(BUFFER*sizeof(char));
		printf("%s\n", inotifytools_filename_from_wd(event->wd));
		strcpy(tmp, inotifytools_filename_from_wd(event->wd));

		char *path;
		if(event->len !=0)
			path = strcat(tmp, event->name);
		else
		{
			path = (char *)malloc(BUFFER*sizeof(char));
			path = strcpy(path, tmp);
		}

		switch(event->mask)
		{
			
			case IN_CREATE:
			//processo evento creazione di un file dentro la dir osservata
			in_create(event, path, found_dir, type_file_list);
			printf("creato file %s\n", path);
			break;

			case IN_CREATE|IN_ISDIR:
			//processo evento creazione di una dir dentro la dir osservata
			in_create_isindir(event, path, found_dir);
			printf("creata dir %s\n", path);
			break;

			case IN_DELETE:
			//processo evento cancellazione file dentro la dir osservata
			printf("cancellato file %s\n", path);
			in_delete(event->wd, path, event->name, type_file_list, found_dir);
			
			break;

			case IN_DELETE|IN_ISDIR:
			//processo evento cancellazione dir dentro dir osservata
			printf("cancellata dir %s\n", path);
			in_delete_isindir(event->wd, path, event->name, type_file_list, found_dir);
			break;

			case IN_MOVED_FROM:
			printf("spostato file %s\n", path);
			in_moved_from(event, event->wd, path, event->name, type_file_list, found_dir);
			break;

			case IN_MOVED_TO:
			printf("spostato nella home file %s\n", path);
			in_moved_to(event, event->wd, path, event->name, type_file_list, found_dir);
			break;


			case IN_MOVE_SELF:
			//rinomina del file o dir
			break;

			case IN_CLOSE_WRITE:
			printf("modificato file %s\n", path);
			in_modify(event, path, type_file_list);
			break;

			case IN_DELETE_SELF:
			//cancellazione della dir osservata
			break;
			
			default:
			printf("ERRORE IMPOSSIBILE PROCESSARE L'EVENTO\n");
		}
		

	}

}



/*!
* \fn		int in_create(struct inotify_event * event, char *path, char* found_dir, char **type_file_list)                
* \brief 	The function in_create adds a new files in the list of controlled files and adds the appropriate
*  		watch for real-time monitoring
*
* \param 	struct inotify_event * event: IN_CREATE event generated by inotify      
* \param        char *path: file's path
* \param	char* found_dir: mediawhere working dir
* \param        char **type_file_list: list of extensions under control
* \return       
* \date         31/01/2011
*/
int in_create(struct inotify_event * event, char *path, char* found_dir, char **type_file_list)
{
	FILE *fp;
	//char *type_file_list[NUM_TYPE_FILE] = {"avi", "mp3", "pdf", "txt", "png"};
	char *name_file = event->name; //pathname of file

	char *string = (char *)malloc(BUFFER*sizeof(char));
	char *tmp=strtok(name_file,".");
	while(tmp != NULL)
	{
		strcpy(string, tmp);//I take the file extension
		tmp=strtok(NULL, ".");
	}
	int i;
	for(i=0; i<NUM_TYPE_FILE; i++)//comparison the file extension with file extensions of interest to me
	{	
		if(strcmp(string, type_file_list[i])==0)
		{
			char *dst = (char *)malloc(BUFFER*sizeof(char)); //4096 caratteri
			strcpy(dst, found_dir);
			char *file_name = strcat(dst, type_file_list[i]);
			fp=fopen(file_name, "a+");
			fprintf(fp,"%s\n",path);//add the newly created file to the corresponding list
			if(strcmp(string, "pdf")==0 || strcmp(string, "txt")==0 || strcmp(string, "doc")==0)
			{
				inotifytools_watch_file(path, IN_CLOSE_WRITE|IN_MOVE_SELF);
				printf("[Append watch] [file=%s] [event=%s]\n", path, "IN_CLOSE_WRITE|IN_MOVE_SELF");
			}
			else
			{
				inotifytools_watch_file(path,IN_MOVE_SELF);//add the watch "IN_MOVE_SELF" to the new file
				printf("[Append watch] [file=%s] [event=%s]\n", path, "IN_MOVE_SELF");
			}
			fclose(fp);


		//echo "FILEBACKEND|DOC|locahost|/home/kinder/mediawhere/in.txt|INSERT\nQUIT"| nc localhost 7777

			char *tosocket = (char *)malloc(BUFFER*sizeof(char));
			strcpy(tosocket, "echo \"FILEBACKEND|");

			//etx becames EXT
			char upper_string[BUFFER];
			strcpy(upper_string, type_file_list[i]);
			to_upper_case(upper_string);

			strcat(tosocket, upper_string);
			strcat(tosocket, "|localhost|");
			strcat(tosocket, path);
			strcat(tosocket, "|INSERT\nQUIT\"| nc localhost 7777");
			printf("[CMD]%s\n", tosocket); 
			system(tosocket);
			break;
		}
	}
	return;
}


/*!
* \fn		int in_create_isindir(struct inotify_event * event, char *path, char *found_dir)                
* \brief 	The function in_create_isindir adds new folder in the list of folder already under control
*		and adds the appropriate watch for this folder
*
* \param 	struct inotify_event * event: IN_CREATE|IN_ISDIR event generated by inotify      
* \param        char *path: file's path
* \param	char* found_dir: mediawhere working dir
* \return       
* \date         31/01/2011
*/

int in_create_isindir(struct inotify_event * event, char *path, char *found_dir)
{
	char *dst = (char *)malloc(BUFFER*sizeof(char)); //I create the path of the file to open (the one containing the controlled dir)
	strcpy(dst, found_dir);
	char *file_name = strcat(dst, "homesubdir");
	FILE *fd = fopen(file_name, "a+");
	fprintf(fd,"%s\n",path);//add the new folder to the file homesubdir
	fclose(fd);
	inotifytools_watch_file(path, IN_MOVE_SELF|IN_CREATE|IN_DELETE|IN_MOVE);//add necessary watch to the new folder
	printf("[Append watch] [dir=%s] [event=%s]\n", path, "IN_MOVE_SELF|IN_CREATE|IN_DELETE|IN_MOVE");
	
}

/*!
* \fn		int in_delete(int wd, char *path, char *name, char **type_list, char *found_dir)
* \brief 	The function in_delete deletes an existing files in the list of controlled files and removes the appropriate
*  		watch for real-time monitoring      
* \param        char *path: file's path
* \param	char *name: filename
* \param 	char **type_list: list of extensions to control
* \param	char* found_dir: mediawhere working dir
* \return       
* \date         31/01/2011
*/

int in_delete(int wd, char *path, char *name, char **type_list, char *found_dir)
{
	FILE *fd, *tmp;//lista dei file controllati
	
	char *token = (char *)malloc(BUFFER*sizeof(char));
	char *tmptoken = strtok(name, ".");

	while(tmptoken != NULL )
	{
		strcpy(token, tmptoken);
		tmptoken = strtok(NULL, ".");

	}

	int delete = 0;
	int i;

	for(i=0; i<NUM_TYPE_FILE; i++)
	{
		if(strcmp(token, type_list[i]) == 0)
		{
			delete = 1;
			break;
		}
		
	}


	if(delete)
	{
		//rimuovo il watch per il file NON E' NECESSARIO...RIMOSSO IMPLICITAMENTE DAL KERNEL
		//inotifytools_remove_watch_by_wd(wd);

		
		char *dst = (char *)malloc(BUFFER*sizeof(char)); //4096 caratteri
		strcpy(dst, found_dir);
		char *file_name = strcat(dst, token);

		fd = fopen(file_name ,"r");
		tmp = tmpfile();
		char tmpstr[BUFFER];
		fgets(tmpstr, BUFFER, fd);//conviene usare la fgets
		//HELP 
		char *path1 = strcat(path, "\n");
		while(!feof(fd))
		{
			if(strcmp(tmpstr, path1)!=0 || strcmp(tmpstr, path)!=0)
				fprintf(tmp, "%s", tmpstr);
			fgets(tmpstr, BUFFER, fd);//conviene usare la fgets
		}
		
		fclose(fd);
		rewind(tmp);
		fd = fopen(file_name, "w");
		fgets(tmpstr, BUFFER, tmp);//conviene usare la fgets
		while(!feof(tmp))
		{
			fprintf(fd, "%s", tmpstr);
			fgets(tmpstr, BUFFER, tmp);//conviene usare la fgets
		}

		fclose(fd);

	//echo "FILEBACKEND|DOC|locahost|/home/kinder/mediawhere/in.txt|DELETE\nQUIT"| nc localhost 7777
		char *tosocket = (char *)malloc(BUFFER*sizeof(char));
			strcpy(tosocket, "echo \"FILEBACKEND|");

			//etx becames EXT
			char upper_string[BUFFER];
			strcpy(upper_string, type_list[i]);
			to_upper_case(upper_string);

			strcat(tosocket, upper_string);
			strcat(tosocket, "|localhost|");

			path[strlen(path)-1]='\0';
			strcat(tosocket, path);
			strcat(tosocket, "|DELETE\nQUIT\"| nc localhost 7777");
			printf("[CMD]%s\n", tosocket); 
			system(tosocket);
	
	}
	

}

/*!
* \fn		int in_delete_isindir(int wd, char *path, char *name, char **type_list, char *found_dir)                
* \brief 	The function in_delete_isindir deletes an existing folder in the list of folder under control
*		and deletes the appropriate watch for this folder
*
* \param 	int wd: dir watch descriptor      
* \param        char *path: file's path
* \param	char *name: dirname
* \param	char **typelist: list of extensions under control
* \param	char* found_dir: mediawhere working dir
* \return       
* \date         31/01/2011
*/


int in_delete_isindir(int wd, char *path, char *name, char **type_list, char *found_dir)
{

	FILE *fd, *tmp;
	char tmpstr[BUFFER];

	//creao il path del file da aprire (quello che contiene le dir controllate)
	char *dst = (char *)malloc(BUFFER*sizeof(char)); //4096 caratteri
	strcpy(dst, found_dir);
	char *file_name = strcat(dst, "homesubdir");

	//elimino la riga della dir cancellata nel file aperto
	fd = fopen(file_name, "r");
	tmp = tmpfile();
	fgets(tmpstr, BUFFER, fd);//conviene usare la fgets
	char *path1 = strcat(path, "\n");
	//tmpstr[strlen(tmpstr)-1]='\0';
	while(!feof(fd))
	{
		//printf("%s\n", tmpstr);
		if(strcmp(tmpstr, path1)!=0 || strcmp(tmpstr, path)!=0)
			fprintf(tmp, "%s", tmpstr);
		fgets(tmpstr, BUFFER, fd);//conviene usare la fgets
		//tmpstr[strlen(tmpstr)-1]='\0';
	}

	fclose(fd);
	rewind(tmp);
	fd = fopen(file_name, "w");
	fgets(tmpstr, BUFFER, tmp);//conviene usare la fgets
	//tmpstr[strlen(tmpstr)-1]='\0';
	while(!feof(tmp))
	{
		fprintf(fd, "%s", tmpstr);
		fgets(tmpstr, BUFFER, tmp);//conviene usare la fgets
		//tmpstr[strlen(tmpstr)-1]='\0';
	}
	
	fclose(fd);		
}

/*!
* \fn		int in_moved_from(struct inotify_event *event, int wd, char *path, char *name, char **type_list, char *found_dir)
* \brief 	The function in_moved_from
*		- 1  recognizes a moving event from dir under control to another dir under control, identifies the new path for file or
*		dir which has caused the event and modifies the watch on these
* 		- 2  recognizes a moving event from dir under control to another external not under control. It only calls in_delete function
*		 in this case
* \param	struct inotify_event *event: IN_MOVED_FROM event generated by inotify
* \param	int wd: watch descriptor
* \param        char *path: file's path
* \param	char *name: filename
* \param 	char **type_list: list of extensions to control
* \param	char* found_dir: mediawhere working dir
* \return       
* \date         31/01/2011
*/


int in_moved_from(struct inotify_event *event, int wd, char *path, char *name, char **type_list, char *found_dir)
{
	struct inotify_event * next_event = inotifytools_next_event( -1 );
 
	if(event->cookie == next_event->cookie && (event->mask != IN_MOVE_SELF)) //eventi moved_from moved_to correlati
	{
		//spostamento da e dentro home
		/*
			1) controllo se il file è dei tipi d'interesse
			2) apro la lista file, aggiorno il path del file
			 
		*/
		FILE *fd, *tmp;//lista dei file controllati

		//creo path della dir destinazione
		char *new_path = (char *)malloc(BUFFER*sizeof(char));
		strcpy(new_path, inotifytools_filename_from_wd(next_event->wd));
		strcat(new_path, next_event->name);

		char *token = (char *)malloc(BUFFER*sizeof(char));
		char *tmptoken = strtok(name, ".");
		while(tmptoken != NULL)
		{
			strcpy(token, tmptoken);
			tmptoken = strtok(NULL, ".");
		}
		
		int delete = 0;
		int i;

		for(i=0; i<NUM_TYPE_FILE; i++)
		{
			if(strcmp(token, type_list[i]) == 0)
			{
				delete = 1;
				break;
			}
		
		}


		if(delete)
		{
			//rimuovo il watch per il file NON E' NECESSARIO...RIMOSSO IMPLICITAMENTE DAL KERNEL
			//inotifytools_remove_watch_by_wd(wd);

		
			char *dst = (char *)malloc(BUFFER*sizeof(char)); //4096 caratteri
			strcpy(dst, found_dir);
			char *file_name = strcat(dst, token);

			fd = fopen(file_name ,"r");
			tmp = tmpfile();
			char tmpstr[BUFFER];
			fgets(tmpstr, BUFFER, fd);//conviene usare la fgets
			char *path1 = strcat(path, "\n");
			while(!feof(fd))
			{
			
				if(strcmp(tmpstr, path1)!=0 || strcmp(tmpstr, path)!=0)
					fprintf(tmp, "%s", tmpstr);
				else
					fprintf(tmp, "%s\n", new_path);
				fgets(tmpstr, BUFFER, fd);//conviene usare la fgets
			}
		
			fclose(fd);
			rewind(tmp);
			fd = fopen(file_name, "w");
			fgets(tmpstr, BUFFER, tmp);//conviene usare la fgets
			while(!feof(tmp))
			{
				fprintf(fd, "%s", tmpstr);
				fgets(tmpstr, BUFFER, tmp);//conviene usare la fgets
			}

			fclose(fd);

			//delete old file
			//echo "FILEBACKEND|DOC|locahost|/home/kinder/mediawhere/in.txt|DELETE\nQUIT"| nc localhost 7777
			char *tosocket = (char *)malloc(BUFFER*sizeof(char));
			strcpy(tosocket, "echo \"FILEBACKEND|");

			//etx becames EXT
			char upper_string[BUFFER];
			strcpy(upper_string, token);
			to_upper_case(upper_string);

			strcat(tosocket, upper_string);
			strcat(tosocket, "|localhost|");

			if(path[strlen(path)-1]=='\n')
				path[strlen(path)-1]='\0';
			strcat(tosocket, path);
			strcat(tosocket, "|DELETE\nQUIT\"| nc localhost 7777");
			printf("[CMD]%s\n", tosocket); 
			system(tosocket);

			//insert new one
			//echo "FILEBACKEND|DOC|locahost|/home/kinder/mediawhere/in.txt|INSERT\nQUIT"| nc localhost 7777
			char *newtosocket = (char *)malloc(BUFFER*sizeof(char));
			strcpy(newtosocket, "echo \"FILEBACKEND|");

			//etx becames EXT
			char newupper_string[BUFFER];
			strcpy(newupper_string, token);
			to_upper_case(newupper_string);

			strcat(newtosocket, newupper_string);
			strcat(newtosocket, "|localhost|");
			strcat(newtosocket, new_path);
			strcat(newtosocket, "|INSERT\nQUIT\"| nc localhost 7777");
			printf("[CMD]%s\n", newtosocket); 
			system(newtosocket);
		}
	}					
	else
	{
			/*
				spostamento del file fuori dalla zona controllata
				1) gestisco l'evento come se fosse una in_delete
				2) devo gestire l'evento successivo che ho deaccodata pensando che fosse IN_MOVED_TO
			*/

			in_delete(wd, path, name, type_list, found_dir);
			//inotifytools_remove_watch_by_wd(wd);
		
	}

}

/*!
* \fn		int in_moved_to(struct inotify_event * event, int wd, char *path, char *name, char **type_list, char *found_dir)
* \brief 	The function in_moved_to recognizes a moving event of dir or file to a dir under control. It simply calls the
*		in_create function
* \param	struct inotify_event *event: IN_MOVED_TO event generated by inotify
* \param	int wd: watch descriptor
* \param        char *path: file's path
* \param	char *name: filename
* \param 	char **type_list: list of extensions to control
* \param	char* found_dir: mediawhere working dir
* \return       
* \date         31/01/2011
*/

int in_moved_to(struct inotify_event * event, int wd, char *path, char *name, char **type_list, char *found_dir)
{
	in_create(event, path, found_dir, type_list);

}

/*!
* \fn		int in_modify(struct inotify_event * event, char *path, char **type_list)
* \brief 	The function in_modify recognizes a IN_CLOSE_WRITE event for a file under control.
* \param	struct inotify_event *event: IN_CLOSE_WRITE event generated by inotify
* \param        char *path: file's path
* \param 	char **type_list: list of extensions to control
* \return       
* \date         31/01/2011
*/


int in_modify(struct inotify_event * event, char *path, char **type_list)
{
	char path_copy[BUFFER];
	strcpy(path_copy, path);
	char *ext = (char *)malloc(BUFFER*sizeof(char));
	char *tmptoken = strtok(path_copy, ".");
	while(tmptoken != NULL)
	{
		strcpy(ext, tmptoken);
		tmptoken = strtok(NULL, ".");
	}
 
	char *tosocket_del = (char *)malloc(BUFFER*sizeof(char));
	strcpy(tosocket_del, "echo \"FILEBACKEND|");

	//etx becames EXT
	char upper_string[BUFFER];
	strcpy(upper_string, ext);
	to_upper_case(upper_string);

	strcat(tosocket_del, upper_string);
	strcat(tosocket_del, "|localhost|");


	strcat(tosocket_del, path);
	strcat(tosocket_del, "|DELETE\nQUIT\"| nc localhost 7777");
	printf("[CMD]%s\n", tosocket_del); 
	system(tosocket_del);

	char *tosocket_ins = (char *)malloc(BUFFER*sizeof(char));
	strcpy(tosocket_ins, "echo \"FILEBACKEND|");

	strcat(tosocket_ins, upper_string);
	strcat(tosocket_ins, "|localhost|");
	strcat(tosocket_ins, path);
	strcat(tosocket_ins, "|INSERT\nQUIT\"| nc localhost 7777");
	printf("[CMD]%s\n", tosocket_ins); 
	system(tosocket_ins);

	return 0;
}

/*!
* \fn		void to_upper_case(char *string)
* \brief 	The function to_upper_case transforms file's extension from lower case to upper case
* \param	char *string: file's extension
* \return      
* \date         31/01/2011
*/


void to_upper_case(char *string)
{
	int i;
	for (i=0; string[i]; i++)
    		string[i] = toupper(string[i]);
}
